package com.foo.ClientActions;

import java.util.Map;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.foo.Entity.RealTimeData;

import com.foo.Entity.TickerInfoData;

import com.foo.Constants.UIMessages;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.foo.DataProvider.*;

public class RealTimeAction extends ActionMapping implements SessionAware, ServletRequestAware, ServletResponseAware {
	private static final long serialVersionUID = 1L;
	
	String[] resultString = null;
	Queue queue = null;
	TopicConnectionFactory factory = null;
	TopicConnection connection = null;
	QueueSender sender = null;
	TopicSession session = null;
	String[] data_to_be_passed=null;
	String retrieved_data="";
	MessageConsumer reciever=null;
	boolean exceptionOccured = false;
	
	protected HttpServletRequest request;
    protected HttpServletResponse response;
	public void init()
    { 
		try
		{
			Properties props = new Properties();
			props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
			props.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
			props.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
			Context ctx;
			ctx = new InitialContext(props);
		
			factory = (TopicConnectionFactory) ctx.lookup("XAConnectionFactory");
			
			try
			{
				connection = factory.createTopicConnection();
			}
			catch(Exception e)
			{
				System.out.println("Connection not closed");
				exceptionOccured = true;
			}
			finally
			{
				if(connection != null && exceptionOccured == true)
				{
					System.out.println("closing the connection");
					connection.close();
					exceptionOccured = false;
					connection = factory.createTopicConnection();
				}	
				
			}
			try
			{
				session = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
			}
			catch(Exception e)
			{
				System.out.println("Session not closed");
				exceptionOccured = true;
			}
			finally
			{
				if(session != null && exceptionOccured == true)
				{
					System.out.println("closing the session");
					session.close();
					exceptionOccured = false;
					session = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
				}
								
			}
			
			Topic topic = (Topic) ctx.lookup("topic/MyRealTimeTopic");
			reciever = session.createConsumer(topic);
			System.out.println("Client started waiting for Server message");
			connection.start();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
    }
		
		public String execute()
		{
			HttpSession session = request.getSession(true);
			RealTimeData tickerdata = null;

			TickerInfoData tickerinfo = null;
			ProviderClient data = new ProviderClient();

			 
			session.setAttribute("realdatareceived","no");
			//get request parameters
			String tickername = request.getParameter("RealTimeCompany").toString();
			
			session.setAttribute("TickerDetails", tickername);
			System.out.println("Received Request is: " +tickername);
			init();

			//Validate if all the input string entered
			if((tickername.equalsIgnoreCase("")))
			{
				session.setAttribute("ServerMessage", UIMessages.REQUIRED_FIELD);
				/*dispatcher = getServletContext().getRequestDispatcher("/realtime.jsp");
				dispatcher.forward(request, response);*/
				return "REALTIME";
			}
			else
			{
				session.setAttribute("ServerMessage",null);
			}
			
			java.sql.Timestamp sqltoDate = new java.sql.Timestamp(System.currentTimeMillis());
			System.out.println("The Date-Time being passed is: " +sqltoDate.toString());
			//data.realtime(tickername,sqltoDate);
			data.getData(tickername, null, sqltoDate, null, null);
			try 
			{
				while (true) 
				{
					if(reciever == null)
					{
						System.out.println("Receier null");
						init();
					}
					if(reciever != null){
			    	Message m = reciever.receive(0);
					
			    	if (m != null) 
			    	{ 
			    		if (m instanceof TextMessage) 
			    		{ 
			            TextMessage message = (TextMessage) m; 
			            System.out.println("Reading message: " + message.getText()); 
			            retrieved_data = message.getText();
			            resultString = retrieved_data.split(","); 
			 			int total_size = resultString .length;
			 			System.out.println("the size of data at client end "+ total_size);
			 			if(connection!=null)
			 			{
			 			connection.close();
			 			}
			 			break;
			    		}	 
			    		else 
			        	{ 
			            break; 
			        	} 
			    	}
					}
				}
				
				}catch (JMSException e) {
					e.printStackTrace();
					/*dispatcher = getServletContext().getRequestDispatcher("/realtime.jsp");
					dispatcher.forward(request, response);*/
					return "REALTIME";
				}
				
			System.out.println("values length: " +resultString.length);
			
			if(resultString != null)
			{
				for(int i=0;i<resultString.length;i+=9) //i+=9
				{
				if(resultString[i].equals("") || resultString[i] == null)
				{
					System.out.println("No more data to print");
					break;
				}
				else
				{
				tickerdata = new RealTimeData();
				tickerinfo = new TickerInfoData();
				tickerdata.setTicker_symbol(resultString[i]);
				tickerdata.setOpen_value(Double.parseDouble(resultString[i+1]));
				tickerinfo.setCompany(resultString[1+3]);
				tickerinfo.setSector_name(resultString[i+4]);
				tickerinfo.setIndustry(resultString[i+5]);
				tickerinfo.setCountry(resultString[i+6]);
				tickerinfo.setState(resultString[i+7]);
				tickerinfo.setMarket_cap(Double.parseDouble(resultString[i+8]));
				
				session.setAttribute("realdatareceived","yes");
				session.setAttribute("realtimedata", tickerdata);
				session.setAttribute("tickerinfodata", tickerinfo);
				session.setAttribute("timevalue", resultString[i+2]);
				}
				}
			}
			else
			{	
				session.setAttribute("realdatareceived","no");
				System.out.println("No message returned");
			}
			
			System.out.println("Exited Loop");
			/*dispatcher = getServletContext().getRequestDispatcher("/realtime.jsp");
			dispatcher.forward(request, response);*/
			return "REALTIME";
		}


		@Override
		public void setServletResponse(HttpServletResponse arg0) {
			this.response = arg0;
			
		}


		@Override
		public void setServletRequest(HttpServletRequest arg0) {
			this.request = arg0;
			
		}


		@Override
		public void setSession(Map<String, Object> arg0) {
			
		}
	}

